﻿using FDStudio.Core.Expressions;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

namespace FDStudio.Core.Entities.Query
{
    /*
     CreatedOn: 2018-01-30
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 查询排序
    /// </summary>
    public class QueryOrder<T> : IQueryOrder<T> where T : class
    {
        static ConditionVisitor visitor = new ConditionVisitor();

        List<SortItem> items = new List<SortItem>();

        public QueryOrder()
        {
            KeySortBy = SortBy.ASC;
        }

        public QueryOrder(SortBy keySortBy)
        {
            KeySortBy = keySortBy;
        }

        public QueryOrder<T> OrderBy<Q>(Expression<Func<T, Q>> orderBy)
        {
            var name = visitor.Resolve(orderBy, null, null, false);
            items.Add(new SortItem { Name = name, SortBy = SortBy.ASC });
            return this;
        }

        public QueryOrder<T> OrderByDescending<Q>(Expression<Func<T, Q>> orderBy)
        {
            var name = visitor.Resolve(orderBy, null, null, false);
            items.Add(new SortItem { Name = name, SortBy = SortBy.DESC });
            return this;
        }

        /// <summary>
        /// 关键字排序方式
        /// </summary>
        public SortBy KeySortBy { get; }

        public string Result
        {
            get
            {
                if (items.Count == 0)
                {
                    return string.Empty;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("ORDER BY ");
                foreach (var item in items)
                {
                    sb.AppendFormat("{0} {1},", item.Name, item.SortBy);
                }
                if (sb.Length > 0)
                {
                    sb.Remove(sb.Length - 1, 1);
                }
                return sb.ToString();
            }
        }

        /// <summary>
        /// 排序项
        /// </summary>
        private class SortItem
        {
            public string Name { get; set; }
            public SortBy SortBy { get; set; }
        }

    }

    /// <summary>
    /// 顺序
    /// </summary>
    public enum SortBy
    {
        ASC, DESC
    }
}

